package team.scau.laboratory_repair.common.shiro;

import lombok.extern.apachecommons.CommonsLog;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import team.scau.laboratory_repair.modules.po.WechatUser;
import team.scau.laboratory_repair.service.WechatUserService;

@Component
@CommonsLog
public class WechatUserRealm extends AuthorizingRealm {
    @Autowired
    private WechatUserService wechatUserService;
    //微信用户的权限待定
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UserToken token = (UserToken) authenticationToken;
        //查出是否有此用户
        WechatUser wechatUser;
        try {
            wechatUser = wechatUserService.findByPhoneNumber(token.getUsername());

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            wechatUser = null;
        }
        if (wechatUser == null) {
            //错误的帐号，没有这个账号
            throw new UnknownAccountException("账号或者密码错误");
        }
        if (!wechatUser.getPassword().equals(new String(token.getPassword()))) {
            throw new IncorrectCredentialsException("账号或者密码错误");
        }

        //若存在，将此用户存放到登录认证info中
        return new SimpleAuthenticationInfo(wechatUser.getPhoneNumber(), wechatUser.getPassword().toUpperCase(), getName());
    }
}
